package com.jn.zhinongbao.adapter;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

public class RegisterActivity extends AppCompatActivity {

    private TextInputEditText etUsername, etPassword, etConfirmPassword, etPhone, etShopName;
    private RadioGroup rgRole;
    private RadioButton rbUser, rbMerchant;
    private TextInputLayout tilShopName;
    private Button btnRegister;
    private TextView tvLogin;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initViews();
        initDatabase();
        setupClickListeners();
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        etConfirmPassword = findViewById(R.id.et_confirm_password);
        etPhone = findViewById(R.id.et_phone);
        etShopName = findViewById(R.id.et_shop_name);
        rgRole = findViewById(R.id.rg_role);
        rbUser = findViewById(R.id.rb_user);
        rbMerchant = findViewById(R.id.rb_merchant);
        tilShopName = findViewById(R.id.til_shop_name);
        btnRegister = findViewById(R.id.btn_register);
        tvLogin = findViewById(R.id.tv_login);
    }

    private void initDatabase() {
        databaseHelper = new DatabaseHelper(this);
    }

    private void setupClickListeners() {
        btnRegister.setOnClickListener(v -> performRegister());
        
        tvLogin.setOnClickListener(v -> {
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        });

        // 监听角色选择变化
        rgRole.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.rb_merchant) {
                // 选择商家，显示店铺名称输入框
                tilShopName.setVisibility(View.VISIBLE);
            } else {
                // 选择用户，隐藏店铺名称输入框
                tilShopName.setVisibility(View.GONE);
                etShopName.setText(""); // 清空店铺名称
            }
        });
    }

    private void performRegister() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String shopName = etShopName.getText().toString().trim();

        // 输入验证
        if (!validateInput(username, password, confirmPassword, phone, shopName)) {
            return;
        }

        // 获取选择的角色
        int role = rbMerchant.isChecked() ? 0 : 1; // 0: 商家, 1: 用户

        // 创建用户对象
        User user;
        if (role == 0) {
            // 商家
            user = new User(username, password, phone, role, shopName);
        } else {
            // 普通用户
            user = new User(username, password, phone, role);
        }

        // 尝试注册
        if (databaseHelper.registerUser(user)) {
            Toast.makeText(this, "注册成功！请登录", Toast.LENGTH_SHORT).show();
            
            // 跳转到登录界面
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "注册失败，用户名可能已存在", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean validateInput(String username, String password, String confirmPassword, 
                                String phone, String shopName) {
        // 验证用户名
        if (TextUtils.isEmpty(username)) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return false;
        }

        if (username.length() < 3) {
            etUsername.setError("用户名至少3位");
            etUsername.requestFocus();
            return false;
        }

        // 检查用户名是否已存在
        if (databaseHelper.isUsernameExists(username)) {
            etUsername.setError("用户名已存在");
            etUsername.requestFocus();
            return false;
        }

        // 验证密码
        if (TextUtils.isEmpty(password)) {
            etPassword.setError("请输入密码");
            etPassword.requestFocus();
            return false;
        }

        if (password.length() < 6) {
            etPassword.setError("密码至少6位");
            etPassword.requestFocus();
            return false;
        }

        // 验证确认密码
        if (TextUtils.isEmpty(confirmPassword)) {
            etConfirmPassword.setError("请确认密码");
            etConfirmPassword.requestFocus();
            return false;
        }

        if (!password.equals(confirmPassword)) {
            etConfirmPassword.setError("两次密码不一致");
            etConfirmPassword.requestFocus();
            return false;
        }

        // 验证手机号
        if (TextUtils.isEmpty(phone)) {
            etPhone.setError("请输入联系电话");
            etPhone.requestFocus();
            return false;
        }

        if (!isValidPhone(phone)) {
            etPhone.setError("请输入有效的手机号");
            etPhone.requestFocus();
            return false;
        }

        // 如果选择商家，验证店铺名称
        if (rbMerchant.isChecked()) {
            if (TextUtils.isEmpty(shopName)) {
                etShopName.setError("请输入店铺名称");
                etShopName.requestFocus();
                return false;
            }
        }

        return true;
    }

    private boolean isValidPhone(String phone) {
        // 简单的手机号验证，可以根据需要完善
        return phone.length() >= 11 && phone.matches("^[0-9]+$");
    }
} 